import http from 'http';
import allApi from './router/index.js';
// import bodyParser from 'body-parser';
import {
  mainFun
} from './mongoDB/index.js';
import paramsFun from './common/paramsFun.js'

// 链接MongoDB
await mainFun();

const server = http.createServer(async (req, res) => {

  const promise = paramsFun(req);

  const {
    params,
    routerPath
  } = await promise;

  // 找不到路由，返回404 Not Found
  if (!routerPath) {
    res.writeHead(404, {
      'Content-Type': 'text/plain; charset=utf-8'
    }).end('Not Found');
    return;
  }

  // 执行
  const resData = await allApi[routerPath](params, req);
  // 返回响应头
  res.writeHead(resData.code || 200, {
    'Content-Type': 'application/json',
    ...resData.responseHeader
  });

  // 接口返回, response 返回的类型为字符串、buffer或者Uint8Array.
  res.end(resData.responseHeader ? resData.data : JSON.stringify({
    code: resData.errorCode || resData.code || 200,
    data: {
      ...resData.data
    },
    msg: resData.msg || 'success',
    request: {
      method: req.method,
      params: params,
    },
  }));
});

server.listen(5004, () => {
  console.log('lister http://localhost:5004');
})